<template>
  <el-input
    :disabled="Boolean(option.noSelect)"
    v-if="option.type == 'input'"
    v-model="option.value"
  />
  <el-select
    v-if="option.type == 'select' || option.type == 'multiple'"
    :multiple="option.type == 'multiple'"
    placeholder="请选择"
    v-model="option.value"
  >
    <el-option
      v-for="(val, key) of option.items"
      :key="key"
      :label="val[`${option.keyName}`]"
      :value="val._id"
    >
    </el-option>
  </el-select>
  <el-upload
    v-if="option.type == 'img'"
    class="uploader"
    :action="`${host}/admin/upload`"
    accept="image/*"
    :headers="setAuthHeaders()"
    :show-file-list="false"
    :on-success="afterUpload"
  >
    <img v-if="option.value" :src="`${host}${option.value}`" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs } from "vue";
import { ElInput, ElSelect, ElOption, ElUpload, ElIcon } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

export default defineComponent({
  name: "EditItem",
  props: {
    option: {
      type: Object,
      required: true,
    },
  },
  components: {
    ElInput,
    ElSelect,
    ElOption,
    ElUpload,
    ElIcon,
    Plus,
  },
  setup(props) {
    const { option } = toRefs(props);
    const host = ref(import.meta.env.VITE_SEREVER_HOST as string);

    function setAuthHeaders() {
      return {
        Authorization: "Bearer " + (localStorage.adminToken || ""),
      };
    }

    function afterUpload(data: any) {
      option.value.value = `/uploads/${data.file.filename}`;
    }

    return { option, setAuthHeaders, host, afterUpload };
  },
});
</script>

<style lang="scss">
.uploader {
  .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    :hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 150px;
      height: 200px;
      line-height: 200px;
      text-align: center;
    }

    .avatar {
      width: 150px;
      height: 200px;
      display: block;
    }
  }
}
</style>
